package com.kc.filter;

import com.kc.util.JWTutil;
import com.kc.util.JwtToken;
import com.kc.util.ResponesBean;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenAccess extends AccessControlFilter {

    /**
     * 只有false才会执行后面的，不做处理后面的接口进行处理。web可重复登录
     *
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String token = httpServletRequest.getHeader("AcessToken");

        httpServletResponse.setCharacterEncoding("UTF-8");

        httpServletResponse.setContentType("application/json;charset=utf-8");

        ResponesBean responesBean = new ResponesBean();

        if (token == null) {
            responesBean.responseError(servletRequest, servletResponse, 415, "未登陆", null);
        } else {
            if (JWTutil.Analysis(token)) {
                JwtToken jwtToken = new JwtToken(token);
                getSubject(servletRequest, servletResponse).login(jwtToken);
                return true;
            } else {
                responesBean.responseError(servletRequest, servletResponse, 415, "权限不足", null);
            }
        }
        return false;
    }
}
